package com.fly;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * Jetty Server.
 */
public class JettyServer
{
    private static final int DEFAULT_PORT = 8080;
    
    private static final String CONTEXT_PATH = "/";
    
    private static final String MAPPING_URL = "/*";
    
    public void run()
        throws Exception
    {
        Server server = new Server(DEFAULT_PORT);
        server.setHandler(servletContextHandler(webApplicationContext()));
        server.start();
        server.join();
    }
    
    /**
     * web.xml -> springmvc
     * 
     * @param context
     * @return
     */
    private ServletContextHandler servletContextHandler(WebApplicationContext context)
    {
        ServletContextHandler handler = new ServletContextHandler();
        handler.setContextPath(CONTEXT_PATH);
        
        ServletHolder holder = new ServletHolder(new DispatcherServlet(context));
        holder.setInitParameter("contextConfigLocation", "classpath:spring-mvc.xml");
        
        handler.addServlet(holder, MAPPING_URL);
        handler.addEventListener(new ContextLoaderListener(context));
        return handler;
    }
    
    /**
     * web.xml -> applicationContext
     * 
     * @return
     */
    private WebApplicationContext webApplicationContext()
    {
        XmlWebApplicationContext context = new XmlWebApplicationContext();
        context.setConfigLocations("classpath:applicationContext.xml");
        return context;
    }
}
